<template>
  <div v-if="!item.meta?.hideInMenu && hasAccess">
    <!-- 有子菜单的情况 -->
    <el-sub-menu
      v-if="hasChildren"
      :index="resolvePath(item.path)"
      :popper-append-to-body="true"
      >
      <template #title>
        <div class="menu-item-content" :class="{ 'is-collapse': isCollapse }">
          <el-icon v-if="item.meta && item.meta.icon">
            <component :is="item.meta.icon" />
          </el-icon>
          <span v-show="!isCollapse" class="menu-item-text">{{ item.meta?.title }}</span>
        </div>
      </template>
      
      <sidebar-item
        v-for="child in item.children"
        :key="child.path"
        :item="child"
        :base-path="resolvePath(item.path)"
        :is-collapse="isCollapse"
      />
    </el-sub-menu>
    
    <!-- 没有子菜单的情况 -->
    <el-menu-item
      v-else
      :index="resolvePath(item.path)"
      :title="isCollapse ? item.meta?.title : ''"
      class="menu-leaf"
      @click="handleMenuClick"
    >
      <div class="menu-item-content" :class="{ 'is-collapse': isCollapse }">
        <el-icon v-if="item.meta && item.meta.icon">
          <component :is="item.meta.icon" />
        </el-icon>
        <span v-show="!isCollapse" class="menu-item-text">{{ item.meta?.title }}</span>
        <slot name="extra" v-if="!isCollapse" />
      </div>
    </el-menu-item>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { RouteRecordRaw } from 'vue-router'

interface Props {
  item: RouteRecordRaw
  basePath: string
  isCollapse: boolean
}

const props = defineProps<Props>()
const router = useRouter()
const userStore = useUserStore()

// 判断是否有子菜单
const hasChildren = computed(() => {
  const children = props.item.children
  if (!children || children.length === 0) {
    return false
  }
  
  // 过滤掉隐藏的子菜单和没有权限的子菜单
  const visibleChildren = children.filter(child => {
    if (child.meta?.hideInMenu) return false
    return checkItemAccess(child)
  })
  return visibleChildren.length > 0
})

// 检查菜单项访问权限
const checkItemAccess = (item: RouteRecordRaw) => {
  // 如果没有登录，不显示需要认证的菜单
  if (item.meta?.requiresAuth && !userStore.isLoggedIn) {
    return false
  }

  // 检查角色权限
  if (item.meta?.roles && Array.isArray(item.meta.roles) && item.meta.roles.length > 0) {
    const hasRole = item.meta.roles.some(role => userStore.hasRole(role))
    if (!hasRole) {
      return false
    }
  }

  // 检查具体权限
  if (item.meta?.permissions && Array.isArray(item.meta.permissions) && item.meta.permissions.length > 0) {
    const hasPermission = item.meta.permissions.some(permission => userStore.hasPermission(permission))
    if (!hasPermission) {
      return false
    }
  }

  return true
}

// 检查当前菜单项是否有访问权限
const hasAccess = computed(() => {
  return checkItemAccess(props.item)
})

// 解析路径
const resolvePath = (routePath: string) => {
  if (routePath.startsWith('/')) {
    return routePath
  }
  // 如果basePath是根路径，直接拼接
  if (props.basePath === '/') {
    return `/${routePath}`
  }
  // 否则正常拼接并清理多余的斜杠
  return `${props.basePath}/${routePath}`.replace(/\/+/g, '/')
}

// 处理菜单点击
const handleMenuClick = async () => {
  const path = resolvePath(props.item.path)
  
  // 检查是否已登录
  if (!userStore.isLoggedIn) {
    console.warn('用户未登录，无法访问:', props.item.meta?.title)
    return
  }
  
  // 检查角色权限
  if (props.item.meta?.roles && Array.isArray(props.item.meta.roles) && props.item.meta.roles.length > 0) {
    const hasRole = props.item.meta.roles.some(role => userStore.hasRole(role))
    if (!hasRole) {
      console.warn(`权限不足，缺少角色权限访问 "${props.item.meta?.title}"，需要角色:`, props.item.meta.roles)
      return
    }
  }
  
  // 检查具体权限
  if (props.item.meta?.permissions && Array.isArray(props.item.meta.permissions) && props.item.meta.permissions.length > 0) {
    const hasPermission = props.item.meta.permissions.some(permission => userStore.hasPermission(permission))
    if (!hasPermission) {
      console.warn(`权限不足，缺少具体权限访问 "${props.item.meta?.title}"，需要权限:`, props.item.meta.permissions)
      return
    }
  }
  
  // 等待DOM更新完成后再进行路由跳转
  await nextTick()
  
  // 检查是否已经是当前路由
  if (router.currentRoute.value.path === path) {
    return
  }
  
  // 执行路由跳转，添加错误处理
  try {
    await router.push(path)
  } catch (error: any) {
    // 忽略重复导航错误
    if (error.name !== 'NavigationDuplicated' && error.name !== 'NavigationCancelled') {
      console.error('路由跳转失败:', error)
    }
  }
}
</script>

<style scoped>
.menu-item-content {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 12px;
  position: relative;
}

.menu-item-text {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: inherit;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  letter-spacing: 0.3px;
}

.menu-item-content.is-active .menu-item-text {
  font-weight: 600;
}

:deep(.el-menu-item .el-icon),
:deep(.el-sub-menu__title .el-icon) {
  font-size: 22px;
  color: rgba(255, 255, 255, 0.75);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  flex-shrink: 0;
  width: 22px;
  height: 22px;
}

:deep(.el-menu-item:hover .el-icon),
:deep(.el-sub-menu__title:hover .el-icon) {
  color: rgba(255, 255, 255, 1);
  transform: scale(1.15) translateX(2px);
}

:deep(.el-menu-item.is-active .el-icon),
:deep(.el-sub-menu.is-active .el-sub-menu__title .el-icon) {
  color: #ffffff;
  transform: scale(1.2);
  filter: drop-shadow(0 2px 4px rgba(255, 255, 255, 0.3));
}

.menu-leaf {
  border-radius: 10px;
  overflow: hidden;
}

:deep(.el-sub-menu__icon-arrow) {
  color: rgba(255, 255, 255, 0.5);
  transition: all 0.3s ease;
  margin-top: -2px;
}

:deep(.el-sub-menu__title:hover .el-sub-menu__icon-arrow) {
  color: rgba(255, 255, 255, 0.8);
}
</style>